<template>
  <div class="stock-in-management">
    <!-- 操作栏：新增按钮 + 搜索 -->
    <div class="operation-bar">
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd" class="add-btn">+ 新增入库</el-button>
      <div class="search-group">
        <el-input
          v-model="searchForm.keyword"
          placeholder="请输入单号/制单人"
          class="search-input"
          @keyup.enter="handleSearch"
          clearable
        />
        <el-select
          v-model="searchForm.supplierId"
          placeholder="选择供应商"
          clearable
          class="filter-select"
          @change="handleSearch"
        >
          <el-option
            v-for="supplier in supplierOptions"
            :key="supplier.supplierId"
            :label="supplier.supplierName"
            :value="supplier.supplierId"
          />
        </el-select>
        <el-select
          v-model="searchForm.warehouseId"
          placeholder="选择仓库"
          clearable
          class="filter-select"
          @change="handleSearch"
        >
          <el-option
            v-for="warehouse in warehouseOptions"
            :key="warehouse.warehouseId"
            :label="warehouse.warehouseName"
            :value="warehouse.warehouseId"
          />
        </el-select>
        <el-date-picker
          v-model="searchForm.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          class="date-picker"
          @change="handleSearch"
          clearable
        />
        <el-button type="primary" icon="el-icon-search" class="search-btn" @click="handleSearch">查询</el-button>
        <el-button type="default" icon="el-icon-refresh" class="reset-btn" @click="handleReset">重置</el-button>
      </div>
    </div>

    <!-- 搜索条件标签 -->
    <div v-if="hasActiveFilters" class="filter-tags">
      <span class="filter-tags-label">当前筛选条件：</span>
      <el-tag
        v-if="searchForm.keyword"
        closable
        @close="clearKeyword"
        class="filter-tag"
      >
        关键词: {{ searchForm.keyword }}
      </el-tag>
      <el-tag
        v-if="searchForm.supplierId"
        closable
        @close="clearSupplier"
        class="filter-tag"
      >
        供应商: {{ getSupplierName(searchForm.supplierId) }}
      </el-tag>
      <el-tag
        v-if="searchForm.warehouseId"
        closable
        @close="clearWarehouse"
        class="filter-tag"
      >
        仓库: {{ getWarehouseName(searchForm.warehouseId) }}
      </el-tag>
      <el-tag
        v-if="searchForm.dateRange && searchForm.dateRange.length === 2"
        closable
        @close="clearDateRange"
        class="filter-tag"
      >
        时间: {{ formatDateRange(searchForm.dateRange) }}
      </el-tag>
    </div>

    <!-- 入库表格 -->
    <div class="table-container">
      <el-table :data="tableData" border class="data-table" v-loading="loading">
        <el-table-column label="序号" type="index" width="40" align="center" />
        <el-table-column prop="boundCode" label="单号" width="140" align="center" />
        <el-table-column prop="operationStatus" label="操作状态" width="80" align="center">
          <template slot-scope="scope">
            <el-tag type="success" size="small">{{ scope.row.operationStatus || '入库' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="制单人" width="80" align="center" />
        <el-table-column prop="creatorTime" label="入库时间" width="100" align="center">
          <template slot-scope="scope">
            {{ formatDate(scope.row.creatorTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="supplierName" label="供应商" width="100" align="center" />
        <el-table-column prop="communityName" label="入库仓库" width="100" align="center" />
        <el-table-column prop="boundDesc" label="备注" width="155" align="center">
          <template slot-scope="scope">
            {{ scope.row.boundDesc || '--' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleView(scope.row)" class="action-btn">查看入库单</el-button>
            <el-button type="text" size="small" @click="handleEdit(scope.row)" class="action-btn">修改</el-button>
            <el-button type="text" size="small" @click="handleDelete(scope.row)" class="action-btn">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.current"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pagination.size"
        layout="prev, pager, next, jumper, sizes, total"
        :total="pagination.total"
        class="pagination"
      />
    </div>


    <!-- 查看入库单详情对话框 -->
    <el-dialog
      title="查看入库单"
      :visible.sync="viewDialogVisible"
      width="70%"
      :close-on-click-modal="false"
    >
      <BoundDetailView
        v-if="viewDialogVisible"
        :bound-id="currentBoundId"
        @close="viewDialogVisible = false"
      />
    </el-dialog>

    <!-- 修改入库单弹窗 -->
    <EditBoundDialog
      :visible.sync="editDialogVisible"
      :boundId="currentBoundId"
      @success="handleEditSuccess"
    />
  </div>
</template>

<script>
import { boundApi } from '@/api/bound'
import { supplierApi } from '@/api/supplier'
import { warehouseApi } from '@/api/warehouse'
import BoundDetailView from './components/BoundDetailView.vue'
import EditBoundDialog from './components/EditBoundDialog.vue'

export default {
  name: 'StockInManagement',
  components: {
    BoundDetailView,
    EditBoundDialog
  },
  data() {
    return {
      loading: false,
      searchForm: {
        keyword: '',
        supplierId: '',
        warehouseId: '',
        dateRange: []
      },
      supplierOptions: [],
      warehouseOptions: [],
      tableData: [],
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      viewDialogVisible: false,
      editDialogVisible: false,
      currentBoundId: null
    }
  },
  computed: {
    hasActiveFilters() {
      return this.searchForm.keyword || 
             this.searchForm.supplierId || 
             this.searchForm.warehouseId || 
             (this.searchForm.dateRange && this.searchForm.dateRange.length === 2)
    }
  },
  created() {
    this.loadData()
    this.loadSupplierOptions()
    this.loadWarehouseOptions()
  },
  methods: {
    // 加载数据
    async loadData() {
      this.loading = true
      try {
        const params = {
          current: this.pagination.current,
          size: this.pagination.size,
          keyword: this.searchForm.keyword || undefined,
          supplierId: this.searchForm.supplierId || undefined,
          warehouseId: this.searchForm.warehouseId || undefined,
          startDate: this.searchForm.dateRange && this.searchForm.dateRange[0] ? this.formatDate(this.searchForm.dateRange[0]) : undefined,
          endDate: this.searchForm.dateRange && this.searchForm.dateRange[1] ? this.formatDate(this.searchForm.dateRange[1]) : undefined,
          boundStatus: 1 // 只查询入库状态的数据
        }
        const response = await boundApi.getBoundPage(params)
        if (response.code === 200) {
          this.tableData = response.data.records || []
          this.pagination.total = response.data.total || 0
          this.pagination.current = response.data.current || 1
        } else {
          this.$message.error(response.message || '查询失败')
        }
      } catch (error) {
        console.error('查询入库单列表失败:', error)
        this.$message.error('查询失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.current = 1
      this.loadData()
    },

    // 加载供应商选项
    async loadSupplierOptions() {
      try {
        const response = await supplierApi.getAllSuppliers()
        if (response.code === 200) {
          this.supplierOptions = response.data || []
        }
      } catch (error) {
        console.error('加载供应商选项失败:', error)
      }
    },

    // 加载仓库选项
    async loadWarehouseOptions() {
      try {
        const response = await warehouseApi.getAllWarehouses()
        if (response.code === 200) {
          this.warehouseOptions = response.data || []
        }
      } catch (error) {
        console.error('加载仓库选项失败:', error)
      }
    },

    // 重置搜索条件
    handleReset() {
      this.searchForm = {
        keyword: '',
        supplierId: '',
        warehouseId: '',
        dateRange: []
      }
      this.pagination.current = 1
      this.loadData()
    },

    // 清除关键词
    clearKeyword() {
      this.searchForm.keyword = ''
      this.handleSearch()
    },

    // 清除供应商
    clearSupplier() {
      this.searchForm.supplierId = ''
      this.handleSearch()
    },

    // 清除仓库
    clearWarehouse() {
      this.searchForm.warehouseId = ''
      this.handleSearch()
    },

    // 清除日期范围
    clearDateRange() {
      this.searchForm.dateRange = []
      this.handleSearch()
    },

    // 获取供应商名称
    getSupplierName(supplierId) {
      const supplier = this.supplierOptions.find(s => s.supplierId === supplierId)
      return supplier ? supplier.supplierName : ''
    },

    // 获取仓库名称
    getWarehouseName(warehouseId) {
      const warehouse = this.warehouseOptions.find(w => w.warehouseId === warehouseId)
      return warehouse ? warehouse.warehouseName : ''
    },

    // 格式化日期范围
    formatDateRange(dateRange) {
      if (!dateRange || dateRange.length !== 2) return ''
      const start = this.formatDate(dateRange[0])
      const end = this.formatDate(dateRange[1])
      return `${start} 至 ${end}`
    },

    // 新增
    handleAdd() {
      this.$router.push('/property-management/add-bound')
    },

    // 编辑
    handleEdit(row) {
      // 打开修改弹窗
      this.currentBoundId = row.boundId
      this.editDialogVisible = true
    },

    // 查看详情
    handleView(row) {
      this.currentBoundId = row.boundId
      this.viewDialogVisible = true
    },

    // 修改成功回调
    handleEditSuccess() {
      this.loadData() // 重新加载数据
    },

    // 删除
    handleDelete(row) {
      this.$confirm('确定要删除这条入库单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await boundApi.deleteBound(row.boundId)
          if (response.code === 200) {
            this.$message.success('删除成功')
            this.loadData()
          } else {
            this.$message.error(response.message || '删除失败')
          }
        } catch (error) {
          console.error('删除入库单失败:', error)
          this.$message.error('删除失败，请稍后重试')
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.pagination.size = val
      this.pagination.current = 1
      this.loadData()
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.pagination.current = val
      this.loadData()
    },


    // 格式化日期
    formatDate(date) {
      if (!date) return '--'
      const d = new Date(date)
      return `${d.getFullYear()}/${String(d.getMonth() + 1).padStart(2, '0')}/${String(d.getDate()).padStart(2, '0')}`
    }
  }
}
</script>

<style scoped>
.stock-in-management {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: 100vh;
}

/* 操作栏样式 - 完全按照图4设计 */
.operation-bar {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 16px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #f0f0f0;
}

/* 表格容器样式 */
.table-container {
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 16px;
}

.add-btn {
  height: 40px;
  padding: 0 24px;
  font-size: 14px;
  font-weight: 500;
  border-radius: 6px;
  background-color: #1890ff;
  border-color: #1890ff;
  box-shadow: 0 2px 4px rgba(24, 144, 255, 0.2);
}

.add-btn:hover {
  background-color: #40a9ff;
  border-color: #40a9ff;
  box-shadow: 0 4px 8px rgba(24, 144, 255, 0.3);
}

.search-group {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
  background-color: #fafafa;
  padding: 16px;
  border-radius: 8px;
  border: 1px solid #e8e8e8;
  transition: all 0.3s ease;
}

.search-group:hover {
  border-color: #d9d9d9;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.search-input {
  width: 150px;
}

.filter-select {
  width: 130px;
}

.date-picker {
  width: 200px;
}

.search-input .el-input__inner,
.filter-select .el-input__inner,
.date-picker .el-input__inner {
  height: 40px;
  border-radius: 8px;
  border: 1px solid #d9d9d9;
  font-size: 14px;
  transition: all 0.3s ease;
  background-color: #fff;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.search-input .el-input__inner:focus,
.filter-select .el-input__inner:focus,
.date-picker .el-input__inner:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 3px rgba(24, 144, 255, 0.15);
  transform: translateY(-1px);
}

.search-input .el-input__inner:hover,
.filter-select .el-input__inner:hover,
.date-picker .el-input__inner:hover {
  border-color: #40a9ff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-btn,
.reset-btn {
  height: 40px;
  padding: 0 20px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 90px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-btn {
  background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
  border: none;
  color: #fff;
}

.search-btn:hover {
  background: linear-gradient(135deg, #40a9ff 0%, #1890ff 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(24, 144, 255, 0.3);
}

.reset-btn {
  background-color: #fff;
  border: 1px solid #d9d9d9;
  color: #595959;
}

.reset-btn:hover {
  background-color: #f5f5f5;
  border-color: #40a9ff;
  color: #40a9ff;
  transform: translateY(-1px);
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.15);
}

/* 筛选标签样式 */
.filter-tags {
  margin-bottom: 16px;
  padding: 12px 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.filter-tags-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
  margin-right: 8px;
}

.filter-tag {
  background-color: #e6f7ff;
  border-color: #91d5ff;
  color: #1890ff;
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.filter-tag:hover {
  background-color: #bae7ff;
  border-color: #69c0ff;
}

.filter-tag .el-tag__close {
  color: #1890ff;
  font-size: 12px;
}

.filter-tag .el-tag__close:hover {
  background-color: #1890ff;
  color: #fff;
}

/* 表格容器样式 */
.table-container {
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.data-table {
  width: 100%;
  border: none;
}

.data-table .el-table__header-wrapper {
  background-color: #fafafa;
}

.data-table th {
  background-color: #fafafa !important;
  color: #262626;
  font-weight: 600;
  font-size: 14px;
  border-bottom: 1px solid #f0f0f0;
  padding: 12px 8px;
}

.data-table td {
  border-bottom: 1px solid #f0f0f0;
  padding: 12px 8px;
  font-size: 14px;
  color: #595959;
}

.data-table tr:hover > td {
  background-color: #f5f5f5;
}

.data-table .el-table__row:nth-child(even) {
  background-color: #fafafa;
}

.data-table .el-table__row:nth-child(even):hover > td {
  background-color: #f0f0f0;
}

/* 操作按钮样式 */
.action-btn {
  color: #1890ff;
  padding: 0 8px;
  margin: 0 4px;
  font-size: 14px;
  border-radius: 4px;
  transition: all 0.3s;
}

.action-btn:hover {
  color: #40a9ff;
  background-color: rgba(24, 144, 255, 0.1);
}

/* 标签样式 */
.el-tag--success {
  background-color: #f6ffed;
  border-color: #b7eb8f;
  color: #52c41a;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 4px;
}

/* 分页容器样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 16px;
  padding: 16px 20px;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.pagination {
  text-align: center;
}

.pagination .el-pager li {
  min-width: 32px;
  height: 32px;
  line-height: 32px;
  margin: 0 4px;
  border-radius: 6px;
  font-size: 14px;
  transition: all 0.3s;
}

.pagination .el-pager li.active {
  background-color: #1890ff;
  color: #fff;
  font-weight: 600;
}

.pagination .el-pager li:hover {
  background-color: #f0f0f0;
}

.pagination .el-pager li.active:hover {
  background-color: #40a9ff;
}

.pagination .btn-prev,
.pagination .btn-next {
  width: 32px;
  height: 32px;
  border-radius: 6px;
  margin: 0 4px;
}

.pagination .btn-prev:hover,
.pagination .btn-next:hover {
  background-color: #f0f0f0;
}

.pagination .el-pagination__jump {
  margin: 0 8px;
}

.pagination .el-pagination__sizes {
  margin: 0 8px;
}

.pagination .el-pagination__total {
  margin: 0 8px;
  color: #595959;
  font-size: 14px;
}

/* 对话框样式 */
.el-dialog {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.el-dialog__header {
  padding: 20px 24px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.el-dialog__title {
  font-size: 18px;
  font-weight: 600;
  color: #262626;
}

.el-dialog__body {
  padding: 24px;
}

.el-dialog__footer {
  padding: 16px 24px 20px;
  border-top: 1px solid #f0f0f0;
}

/* 加载状态样式 */
.el-loading-mask {
  background-color: rgba(255, 255, 255, 0.8);
}

.el-loading-spinner {
  color: #1890ff;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-input {
    width: 180px;
  }
  
  .filter-select {
    width: 140px;
  }
  
  .date-picker {
    width: 200px;
  }
}

@media (max-width: 768px) {
  .stock-in-management {
    padding: 12px;
  }
  
  .operation-bar {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .search-group {
    justify-content: center;
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input,
  .filter-select,
  .date-picker {
    width: 100%;
    max-width: 300px;
    margin: 0 auto 8px;
  }
  
  .search-btn,
  .reset-btn {
    width: 100%;
    max-width: 300px;
    margin: 0 auto;
  }
  
  .data-table th,
  .data-table td {
    padding: 8px 4px;
    font-size: 12px;
  }
  
  .action-btn {
    font-size: 12px;
    padding: 0 4px;
    margin: 0 2px;
  }
}

@media (max-width: 480px) {
  .pagination-container {
    padding: 8px 12px;
  }
  
  .pagination .el-pager li {
    min-width: 28px;
    height: 28px;
    line-height: 28px;
    margin: 0 2px;
  }
  
  .pagination .btn-prev,
  .pagination .btn-next {
    width: 28px;
    height: 28px;
    margin: 0 2px;
  }
}
</style>